package com.atguigu.medical.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.medical.realtime.app.BaseApp;
import com.atguigu.medical.realtime.bean.UserRegisterBean;
import com.atguigu.medical.realtime.common.Constant;
import com.atguigu.medical.realtime.util.DateUtil;
import com.atguigu.medical.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/28 14:47
 */
public class DwsUserUserRegisterWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsUserUserRegisterWindow().init(
            40001,
            2,
            "Dws_05_DwsUserUserRegisterWindow",
            Constant.TOPIC_DWD_USER_REGISTER
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 把数据封装为 pojo 类型
        SingleOutputStreamOperator<UserRegisterBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<UserRegisterBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
        
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserRegisterBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_register_window", UserRegisterBean.class));
    }
    
    private SingleOutputStreamOperator<UserRegisterBean> windowAndAgg(
        SingleOutputStreamOperator<UserRegisterBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserRegisterBean>() {
                    @Override
                    public UserRegisterBean reduce(UserRegisterBean value1,
                                                   UserRegisterBean value2) throws Exception {
                        value1.setNewUserCt(value1.getNewUserCt() + value2.getNewUserCt());
                        return value1;
                    }
                },
                new ProcessAllWindowFunction<UserRegisterBean, UserRegisterBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserRegisterBean> elements,
                                        Collector<UserRegisterBean> out) throws Exception {
                        UserRegisterBean bean = elements.iterator().next();
    
                        bean.setStt(DateUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(DateUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<UserRegisterBean> parseToPojo(DataStreamSource<String> stream) {
        return stream.map(new MapFunction<String, UserRegisterBean>() {
            @Override
            public UserRegisterBean map(String value) throws Exception {
                JSONObject obj = JSON.parseObject(value);
                return new UserRegisterBean("", "", 1L, obj.getLong("ts"));
            }
        });
    }
}
